package com.yjy.fuyao.stu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjy.fuyao.stu.entity.Chapter;
import com.yjy.fuyao.stu.entity.Video;
import com.yjy.fuyao.stu.entity.vo.ChapterVo;
import com.yjy.fuyao.stu.entity.vo.VideoVo;
import com.yjy.fuyao.stu.mapper.ChapterMapper;
import com.yjy.fuyao.stu.service.ChapterService;
import com.yjy.fuyao.stu.service.VideoService;
import com.yjy.fuyao.utils.exception.BusinessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author yjy
 * @since 2021-08-17
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Resource
    private VideoService videoService;

    @Override
    public List<ChapterVo> nestedList(String courseId) {
        List<ChapterVo> chapterVoList = new ArrayList<>();
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId).orderByAsc("sort");
        List<Chapter> chapters = baseMapper.selectList(queryWrapper);
        for (Chapter chapter:chapters) {
            ChapterVo chapterVo = new ChapterVo();
            chapterVo.setId(chapter.getId());
            chapterVo.setTitle(chapter.getTitle());
            List<VideoVo> children = new ArrayList<>();
            QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
            videoQueryWrapper
                    .eq("course_id",courseId)
                    .eq("chapter_id",chapter.getId())
                    .orderByAsc("sort");
            List<Video> videos = videoService.list(videoQueryWrapper);
            for (Video video:videos) {
                VideoVo videoVo = new VideoVo();
                videoVo.setId(video.getId());
                videoVo.setVideoSourceId(video.getVideoSourceId());
                videoVo.setTitle(video.getTitle());
                videoVo.setFree((video.getIsFree() == 1));
                children.add(videoVo);
            }
            chapterVo.setChildren(children);
            chapterVoList.add(chapterVo);
        }
        return chapterVoList;
    }

    @Override
    public boolean removeChapterById(String id) {
        //根据id查询是否存在视频，如果有则提示用户尚有子节点
        if(videoService.getCountByChapterId(id)){
            throw new BusinessException("该分章节下存在视频课程，请先删除视频课程",20001);
        }
        Integer result = baseMapper.deleteById(id);
        return null != result && result > 0;
    }

    @Override
    public boolean removeByCourseId(String courseId) {
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id",courseId);
        Integer result = baseMapper.delete(chapterQueryWrapper);
        return null != result && result > 0;
    }
}
